require "Common/define"
require "Logic/Config"
require "Common/functions"
require 'FairyGUI'

UIEmail = {}
HelperFunc.SetUIEnv(UIEmail)
local this = UIEmail;

this.LuaBehaviour = nil;
this.transform = nil;
this.gameObject = nil;

this.hasInit = false;
this.emailList = nil;
this.noEmail = nil;
this.content = nil;
this.btn_delete = nil;
this.btn_get = nil;
this.bg = nil;
this.btn_back = nil;
this.bgClose = nil

this.emailDetails = nil;
this.emailTitle = nil;
this.emailInfo = nil;
this.sender = nil;
this.date = nil;
this.reward = nil;
---@type GList
this.rewardList = nil;
this.btn_sure = nil;
this.btn_getReward = nil;
this.detailsBack = nil;

this.curEmailDetails = nil;
this.emailDatalist = {};
this.emailDetailsCtrl = nil;
this.emailCtrl = nil;
this.isRead = nil;
this.isAll = nil;

function UIEmail.Init()
    local name, packageName = getUIName(PanelResNames.UIEmail);
    panelMgr:Push(name, packageName, this.OnCreate, Config.useLocalUI);
end

function UIEmail.OnCreate(obj)
    bg = obj:GetChild("n15");
    bgClose = obj:GetChild("bgClose")
    BgClose = obj:GetChild("BgClose")
    
    btn_delete = obj:GetChild("btn_delete");
    btn_get = obj:GetChild("btn_get");
    noEmail = obj:GetChild("none");
    content = obj:GetChild("content");
    content:SetVirtual();
    --邮件详情页
    emailDetails = obj:GetChild("emailDetails");
    detailsBack = emailDetails:GetChild("detailClose");
    emailTitle = emailDetails:GetChild("detailsTitle");
    emailInfo = emailDetails:GetChild("detailsInfo");
    sender = emailDetails:GetChild("sender");
    date = emailDetails:GetChild("date");
    rewardList = emailDetails:GetChild("rewardlist");
    btn_sure = emailDetails:GetChild("btn_sure");
    btn_getReward = emailDetails:GetChild("btn_get");
    rewardList.itemRenderer = this.showRewardInfo;
    rewardList:SetVirtual()
    this.Btn_PetFrameRoot = emailDetails:GetChild("Comp_PetFrame")
    this.Btn_PetFrame = this.Btn_PetFrameRoot:GetChild("Btn_PetFrame")
    emailCtrl = obj:GetController("emailCtrl");
    emailCtrl.selectedPage = "noEmail"
    emailDetailsCtrl = obj:GetController("emailDetailsCtrl");
    emailDetailsCtrl.selectedPage = "hideDetails";
    this.emailPetModelTable = {}
    this.addEvent();
    this.initUI();
end

function UIEmail.OnEnable()
    this.LocalListenEvent();
end

function UIEmail.OnDisable()
    if nil ~= this.emailPetModelTable then
        PetManager.RemovePetModelTable(this.emailPetModelTable)
    end
    this.LocalCloseEvent();
end

function UIEmail.OnDestroy()
    this.removeEvent();
end

function UIEmail.LocalListenEvent()
    ListenEvent(Config.EventType.Fresh_Email, this.initUI);
    ListenEvent(Config.EventType.Fresh_Email, this.updateCurEmailReward);
    ListenEvent(Config.EventType.GetEmailRewardTip, this.GetEmailRewardTip);
end

function UIEmail.LocalCloseEvent()
    CloseEvent(Config.EventType.Fresh_Email, this.initUI);
    CloseEvent(Config.EventType.Fresh_Email, this.updateCurEmailReward);
    CloseEvent(Config.EventType.GetEmailRewardTip, this.GetEmailRewardTip);
end

function UIEmail.addEvent()
    --bg.onClick:Add(this.onClickBack)
    BgClose.onClick:Add(this.onClickBack)
    bgClose.onClick:Add(this.onClickBack)
    btn_delete.onClick:Add(this.onClickDelete)
    btn_get.onClick:Add(this.onClickGet)
    btn_getReward.onClick:Add(this.onClickGetReward)
    btn_sure.onClick:Add(this.onClickSure)
    detailsBack.onClick:Add(this.onClickSure)
end

function UIEmail.removeEvent()
    --bg.onClick:Remove(this.onClickBack)
    BgClose.onClick:Remove(this.onClickBack)
    bgClose.onClick:Remove(this.onClickBack)
    btn_delete.onClick:Remove(this.onClickDelete)
    btn_get.onClick:Remove(this.onClickGet)
    btn_getReward.onClick:Remove(this.onClickGetReward)
    btn_sure.onClick:Remove(this.onClickSure)
    detailsBack.onClick:Remove(this.onClickSure)
    emailInfo.onClickLink:Remove(this.OnClickLinkUrl)
end

function UIEmail.initUI()
    --获取email数据
    emailDatalist = logicMgr.EmailManager.getEmailList();
    local midList={}
    for _,v in ipairs(emailDatalist)do
        local data=v
        local dead_time = math.floor(tonumber(data["deadTime"]))
        if not(dead_time > 0 and HelperFunc.GetServerTime() >= dead_time)  then
            table.insert(midList,v)
        end
    end
    emailDatalist=midList
    table.sort(emailDatalist, this.sort)
    emailCtrl.selectedPage = "hadEmail"
    content.itemRenderer = this.ItemRenderer;
    content.numItems = #emailDatalist;
    HelperFunc.ListTranstionPlay(content)

    if #emailDatalist <= 0 then
        emailCtrl.selectedPage = "noEmail"
        content.numItems = 0;
    end

end

function UIEmail.ItemRenderer(index, obj)
    local emailItem = obj;
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.EmailItemList);
    if ctrlItem ~= nil then
        ctrlItem.initData(emailItem, emailDatalist[index + 1]);
    end
end

function UIEmail.showDetails(emailData)
    emailDetailsCtrl.selectedPage = "showDetails";
    --邮件内容
    local strParam = {}
    if emailData.param then
        for i, v in pairs(emailData.param) do
            if emailData.cfgId == 39 or emailData.cfgId == 38 then
                table.insert(strParam, 2^(8-v));
            else
                table.insert(strParam, v);
            end
        end
    end
    if emailData.cfgId == 41 then
        table.insert(strParam,  getLanguage("Place_0"..logicMgr.FriendBattleManager.GetGroup()));
    end
    emailTitle.text = emailData["mailSubject"];
    emailInfo.text = emailData["mailContent"];

    if #strParam == 1 then
        emailInfo.text = string.format(emailData["mailContent"], strParam[1]);
    elseif #strParam == 2 then
        emailInfo.text = string.format(emailData["mailContent"], strParam[1], strParam[2]);
    elseif #strParam == 3 then
        emailInfo.text = string.format(emailData["mailContent"], strParam[1], strParam[2], strParam[3]);
    end
    if emailData.cfgId == 31 then
        local petName = getLanguage(G.dataTable["t_elvesgene"][tostring(emailData.param["bodyGene"])]["f_Name"]);
        emailInfo.text = string.format(emailData["mailContent"], emailData.param["playerName"], petName);
    elseif emailData.cfgId == 210 then
        emailInfo.text = string.format(emailData["mailContent"], getLanguage(G.dataTable["t_headframe"][tostring(strParam[1])].f_FrameName));
    elseif emailData.cfgId == 211 then
        emailInfo.text = string.format(emailData["mailContent"], getLanguage(G.dataTable["t_medal"][tostring(strParam[1])].f_MedalName));
    elseif emailData.cfgId == 212 then
        emailInfo.text = string.format(emailData["mailContent"], getLanguage(G.dataTable["t_item"][tostring(strParam[1])].f_ItemName));
    elseif emailData.cfgId == 209 or emailData.cfgId == 217 then
        --local tableData = logicMgr.NoticeManager.getSevenRankTableDataByType(emailData.param["type"]);
        --emailInfo.text = string.format(emailData["mailContent"], getLanguage(tableData.f_IconName), emailData.param["rank"]);
        emailInfo.text = string.format(emailData["mailContent"],  getLanguage("RaceRankTips"..strParam[1]), strParam[2]);
    elseif emailData.cfgId == 49 then
        local cfg_arena_matching = logicMgr.ArenaManager.getArenaMatchingConfigByRank( emailData.param["dan"] )
        emailInfo.text = string.format(emailData["mailContent"],  cfg_arena_matching and getLanguage(cfg_arena_matching.f_RankName) or "--")
    elseif emailData.cfgId == 213 then
        local player_name = logicMgr.HeroManager.GetRoleName() or "--"
        emailInfo.text = string.format(emailData["mailContent"],  player_name)
    elseif emailData.cfgId == 234 then
        emailInfo.text = string.format(emailData["mailContent"],  getLanguage(strParam[1]))
    elseif emailData.cfgId == 236 then
        local conf = logicMgr.CostManager.getCostServerTableDataById(strParam[1]);
        if conf.f_StoreName then
            emailInfo.text = string.format(emailData["mailContent"],  getLanguage(conf.f_StoreName))
        end
    elseif emailData.cfgId == 237 then
        local conf = G.dataTable["t_question"][tostring(strParam[1])]
        if conf then
            emailInfo.text = string.format(emailData["mailContent"],  getLanguage(conf.f_Title))
        end
    end
    emailInfo.onClickLink:Remove(UIEmail.OnClickLinkUrl)
    emailInfo.onClickLink:Add(UIEmail.OnClickLinkUrl)

    sender.text = emailData["senderName"];
    if emailData.cfgId == 213 then
        sender.text = string.format(emailData["senderName"], emailData.param["sender"])
    end
    local time = os.date("%Y-%m-%d", math.floor(tonumber(emailData["sendTime"]) / 1000));
    date.text = time;
    curEmailDetails = emailData;
    local rewardCtrl = emailDetails:GetController("rewardCtrl");
    local stateCtrl = emailDetails:GetController("stateCtrl");

    if emailData["rewards"] ~= nil and #emailData["rewards"] > 0 then
        rewardCtrl.selectedPage = "showReward";
        local TwoLine = emailDetails:GetController("TwoLine");
        if #emailData["rewards"] > 5 then
            TwoLine.selectedIndex = 1;
        else
            TwoLine.selectedIndex = 0;
        end
        this.updateCurEmailReward();
        if emailData.mailRead == 0 then
            emailHandler.reqReadMail(emailData["mailId"]);
        end
    else
        rewardCtrl.selectedPage = "noReward";

        stateCtrl.selectedPage = "sureState";
        emailHandler.reqReadMail(emailData["mailId"]);
    end

    if nil ~= emailData.attachmentPet then
        rewardCtrl:SetSelectedIndex(1)
        this.Btn_PetFrameRoot.visible = true
        if tonumber(emailData["mailGetItems"]) == 0  then
            -- stateCtrl:SetSelectedIndex(0)
            this.Btn_PetFrame:GetController("cantSelect"):SetSelectedIndex(0)
            emailHandler.reqReadMail(emailData["mailId"])
        else
            -- stateCtrl:SetSelectedIndex(0)
            this.Btn_PetFrame:GetController("cantSelect"):SetSelectedIndex(1)
        end

        local _newPetInfo = PetManager.GetNewPetInfo(emailData.attachmentPet,HeroManager.GetRoleName())
        local _petMutationLevel = PetManager.GetMutationLevel(_newPetInfo.genes)
        this.Btn_PetFrame:GetController("level"):SetSelectedIndex(_petMutationLevel - 1)
        this.Btn_PetFrame:GetChild("frame").url = PetManager.GetMutationLevelFrameIcon(_petMutationLevel)

        --显示宠物模型
        if nil == this.emailPetModelTable then
            this.emailPetModelTable = {}
        end
        PetManager.LoadItemPetModel(_newPetInfo,this.emailPetModelTable,1,this.Btn_PetFrame:GetChild("Model_Pet"))
    else
        this.Btn_PetFrameRoot.visible = false
    end
end

--刷新当前邮件奖励
function UIEmail.updateCurEmailReward()
    for i = 1, #emailDatalist do
        if curEmailDetails and curEmailDetails["mailId"] == emailDatalist[i]["mailId"] then
            curEmailDetails = emailDatalist[i];

            if tonumber(curEmailDetails["mailGetItems"]) == 0 
                and (#curEmailDetails["rewards"] > 0 or curEmailDetails.attachmentPet) then
                local stateCtrl = emailDetails:GetController("stateCtrl");
                stateCtrl.selectedPage = "getState";
                isRead = false;
            else
                local stateCtrl = emailDetails:GetController("stateCtrl");
                stateCtrl.selectedPage = "sureState";
                isRead = true;
            end

            rewardList.numItems = #curEmailDetails["rewards"];
        end
    end
end

function UIEmail.showRewardInfo(index, obj)
    index = index + 1
    local ctrlItem = CtrlManager.GetCtrl(PanelNames.Item);
    if ctrlItem ~= nil then
        curEmailDetails["rewards"][index]["mailGet"] = curEmailDetails["mailGetItems"];
        ctrlItem.initData(obj, curEmailDetails["rewards"][index], 3);
    end
end

--一键删除
function UIEmail.onClickDelete()
    emailHandler.reqDeleteMail(-1);
end

--一键领取
function UIEmail.onClickGet()
    local count = 0;
    for i = 1, #emailDatalist do
        local mail = emailDatalist[i]
        if mail["mailGetItems"] == 0 and not logicMgr.EmailManager.IsOutDate(mail.mailId) then
            local rewards = mail["rewards"];
            if #rewards > 0 then
                for j = 1, #rewards do
                    local itemModelId = rewards[j]["itemModelId"];
                    local isGet = this.isBagFull(itemModelId);
                    if not isGet then
                        UISysTips.AddMsg("背包已满，请先清理哦!");
                        return ;
                    end
                end
                count = count + 1;
            end
        end
    end
    if count == 0 then
        UISysTips.AddMsg("没有可领取的附件")
    else
        emailHandler.reqGetMailReward(-1)
    end
end

function UIEmail.onClickSure()
    emailDetailsCtrl.selectedPage = "hideDetails";
end

--详情中单点领取奖励
function UIEmail.onClickGetReward()
    if logicMgr.EmailManager.IsOutDate(curEmailDetails.mailId) then
        UISysTips.AddMsg(getLanguage("ErrorCode_703"))--邮件已过期
        return
    end
    if curEmailDetails.attachmentPet and BrokerManager.CheckPetBagMaxCount() then
        UISysTips.AddMsg(getLanguage("PETEMAIL_PetBagMaxCountError"))
        return
    end
    if curEmailDetails["rewards"] ~= nil and #curEmailDetails["rewards"] > 0 then
        for i = 1, #curEmailDetails["rewards"] do
            local itemModelId = curEmailDetails["rewards"][i]["itemModelId"];
            local isGet = this.isBagFull(itemModelId);
            if not isGet then
                UISysTips.AddMsg("背包已满，请先清理哦!");
                return ;
            end
        end
    end
    emailHandler.reqGetMailReward(curEmailDetails["mailId"])
end

function UIEmail.isBagFull(itemModelId)
    --[[local bagLimitData = decodeJsonStrToTabel(G.dataTable["t_global"][tostring(14)].f_string_value);
    local tabType = logicMgr.ItemManager.getItemTabType(itemModelId)
    if tabType == EnumConst.ItemTableEnum.Equip then
        local itemLimit = dataTable.getDataTableByStringId("t_equip",itemModelId,"f_Add")
        local itemNum = logicMgr.EquipManager.getEquipCountById(itemModelId)
        local limitNum = bagLimitData[EnumConst.ItemTableEnum.Equip + 1];
        local allEquipData = logicMgr.EquipManager.getEquipList();
        if #allEquipData >= limitNum or itemNum >= itemLimit then
            return false;
        end
    elseif tabType == EnumConst.ItemTableEnum.Item then
        local itemLimit = dataTable.getDataTableByStringId("t_item",itemModelId,"f_Add")
        local itemNum = logicMgr.ItemManager.getItemCountbyModelId(itemModelId)
        local limitNum = bagLimitData[EnumConst.ItemTableEnum.Item + 1];
        local allItemData = logicMgr.ItemManager.getItemDataByTabType(EnumConst.ItemTableEnum.Item);
        if #allItemData >= limitNum or  itemNum >= itemLimit then
            return false;
        end
    elseif tabType == EnumConst.ItemTableEnum.Hero then
        local limitNum = bagLimitData[EnumConst.ItemTableEnum.Hero + 1];
        local allHeroData = logicMgr.ItemManager.getItemDataByTabType(EnumConst.ItemTableEnum.Hero);
        if #allHeroData >= limitNum then
            return false;
        end
    elseif tabType == EnumConst.ItemTableEnum.Fragment then
        -- local limitNum = dataTable.getDataTableByStringId("t_item",itemModelId,"f_Add")--bagLimitData[EnumConst.ItemTableEnum.Fragment + 1];
        -- local allFragmentData = logicMgr.ItemManager.getItemDatabyTabType(EnumConst.ItemTableEnum.Fragment, true);
        -- if #allFragmentData >= limitNum then
        --     return false;
        -- end
    end]]
    return true;
end

function UIEmail.onClickBack()
    closeUI(PanelNames.UIEmail)
end

--出通用的获得奖励页面
---@param addItems TempItemInfo[]
function UIEmail.GetEmailRewardTip(addItems,mailIdList)
    if #addItems ~= 0 then
        logicMgr.UIShowManager.ShowRewardByTempItemInfo(addItems)
        --showUI(PanelNames.UICommonItemGet, nil, nil, 2, Rewardlist);
    else
        if mailIdList==nil then
            UISysTips.AddMsg("没有可领取的附件");
        end
       
    end
end

--邮件排序：--a)亮态>灰态  --b)相同状态根据时间，最近时间优先
function UIEmail.sort(a, b)
    --[[
    if (a.mailRead ~= b.mailRead) then
        return a.mailRead < b.mailRead
    end
    if (a.mailGetItems ~= b.mailGetItems) then
        return a.mailGetItems < b.mailGetItems
    end
    --]]
    if (a.mailStatue ~= b.mailStatue) then
        return a.mailStatue < b.mailStatue
    end
    if a.sendTime ~= b.sendTime then
        return a.sendTime > b.sendTime
    end
    return a.mailId < b.mailId

end

function UIEmail.OnClickLinkUrl(content)
    if content and not string.IsNilOrEmpty(content.data) then 
        UnityEngine.Application.OpenURL(tostring(content.data))
    end
end

return UIEmail;